package org.penguin.boot.security.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

import static java.lang.String.format;

/**
 * @author : cyhch
 * @version : 1.0
 * @createdTime : 2023/12/19 20:43
 * @since : 1.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors()
          .forEach(error -> {
                       if (errors.containsKey(error.getField())) {
                           errors.put(error.getField(), format("%s, %s", errors.get(error.getField()), error.getDefaultMessage()));
                       } else {
                           errors.put(error.getField(), error.getDefaultMessage());
                       }
                   });
        return ResponseEntity.badRequest().body(errors);
    }
}
